package com.huarui.partner.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.ewaf.framework.action.BaseAction;
import org.ewaf.framework.model.ListModel;
import org.ewaf.framework.util.HttpUtil;
import com.huarui.area.model.Area;
import com.huarui.area.service.AreaService;
import com.huarui.company.model.Company;
import com.huarui.company.service.CompanyService;
import com.huarui.company.util.JoinStringUtil;
import com.huarui.dictionary.service.DictionaryReadOnlyService;
import com.huarui.notice.INoticeService;
import com.huarui.notice.Notice;
import com.huarui.partner.model.Partner;
import com.huarui.partner.model.PartnerAddress;
import com.huarui.partner.model.PartnerListModel;
import com.huarui.partner.service.PartnerAddressService;
import com.huarui.partner.service.PartnerService;
import com.huarui.user.model.SessionMessage;
import com.huarui.user.security.UserHolder;
import com.huarui.util.ConstantUtil;
import com.huarui.util.PinyinToolkit;

/**
 * xzz
 * 
 * @author Administrator
 * 
 */
public class PartnerAction extends BaseAction {

	private static final long serialVersionUID = -5978425442471324291L;

	@SuppressWarnings("unused")
	private Logger logger = Logger.getLogger(PartnerAction.class);

	private Integer areaId;
	private PartnerService partnerService;
	private String dir;
	private String sort;
	private Integer start;
	private Integer limit;
	private String type;
	private String qualify;
	private SessionMessage sessionMessage;
	private CompanyService companyService;
	private AreaService areaService;
	private String queryParam;
	private INoticeService noticeService;
	private JSONObject jsonResult = new JSONObject();
	private PartnerAddressService partnerAddressService;
	private DictionaryReadOnlyService dictionaryReadOnlyService;
	private Map<String, Object> resultMap = new HashMap<String, Object>();

	public INoticeService getNoticeService() {
		return noticeService;
	}

	public void setNoticeService(INoticeService noticeService) {
		this.noticeService = noticeService;
	}

	public Map<String, Object> getResultMap() {
		return resultMap;
	}

	public PartnerAddressService getPartnerAddressService() {
		return partnerAddressService;
	}

	public void setPartnerAddressService(
			PartnerAddressService partnerAddressService) {
		this.partnerAddressService = partnerAddressService;
	}

	public String getQueryParam() {
		return queryParam;
	}

	public void setQueryParam(String queryParam) {
		this.queryParam = queryParam;
	}

	public void setAreaService(AreaService areaService) {
		this.areaService = areaService;
	}

	public void setCompanyService(CompanyService companyService) {
		this.companyService = companyService;
	}

	public SessionMessage getSessionMessage() {
		return sessionMessage;
	}

	public void setSessionMessage(SessionMessage sessionMessage) {
		this.sessionMessage = sessionMessage;
	}

	public String getDir() {
		return dir;
	}

	public void setDir(String dir) {
		this.dir = dir;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public Integer getAreaId() {
		return areaId;
	}

	public void setAreaId(Integer areaId) {
		this.areaId = areaId;
	}

	public void setPartnerService(PartnerService partnerService) {
		this.partnerService = partnerService;
	}

	public String inputCreate() {
		return "toInput";
	}

	public String index() {

		return "index";
	}
	public DictionaryReadOnlyService getDictionaryReadOnlyService() {
		return dictionaryReadOnlyService;
	}

	public void setDictionaryReadOnlyService(
			DictionaryReadOnlyService dictionaryReadOnlyService) {
		this.dictionaryReadOnlyService = dictionaryReadOnlyService;
	}

	public String query() throws IOException {

		SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();
		PartnerListModel lm = getModelUtil(httpServletRequest);
		Integer ownerId = sessionMessage.getCompanyId();

		ListModel<Partner> listModel = null;
		try {
			listModel = partnerService.getAllPartnerByOwnerId(lm, ownerId);
		} catch (Exception e) {
e.printStackTrace();
			resultMap.put("failure", "服务器正则升级中...");

			return "json";

		}

		JSONArray root = JSONArray.fromObject(listModel.getResult());
		// 分页信息
		resultMap.put("totalProperty", listModel.getTotal());
		resultMap.put("page", lm.getPage());
		resultMap.put("root", root);

		return "json";
	}

	/**
	 * 分页参数设置
	 * 
	 * @author jiwei.yi
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private ListModel generateListModelParams() {
		ListModel listModel = new ListModel();
		listModel.setPageSize(limit == null ? ConstantUtil.PAGESIZE : limit);
		listModel.setPage(start == null && limit == null ? 1 : start / limit
				+ 1);
		listModel.setOrderBy(sort);
		if (dir != null) {
			listModel.setDesc(dir.equals(ConstantUtil.DESC) ? true : false);
		} else {
			listModel.setDesc(true);
		}
		return listModel;
	}

	@SuppressWarnings("unchecked")
	public String save() throws IOException {	

		sessionMessage = UserHolder.getCurrentSessionMessage();

		Integer ownerId = sessionMessage.getCompanyId();

		JSONArray ja = JSONArray.fromObject(queryParam);

		String arr[] = new String[2];

		for (int i = 0; i < ja.size(); i++) {

			arr[i] = ja.get(i).toString();

		}

		JSONObject partnerJson = JSONObject.fromObject(arr[0]);

		Partner partner = (Partner) JSONObject.toBean(partnerJson,Partner.class);
		Integer partnerId = partner.getId();
				
		if(partner.getCompanyId()==null){
			
			partner.setCompanyId(0);
			
		}
		
		if (partner.getDiscount() == null) {

			partner.setDiscount(100);

		}	
		
		if (partnerId != null) {
			/**
			 * 修改客户信息 ，通过前台传过来的ID判断
			 */

			List<PartnerAddress> partnerAddressUpdateList = new ArrayList<PartnerAddress>();
			List<PartnerAddress> partnerAddressAddList = new ArrayList<PartnerAddress>();
			List<PartnerAddress> partnerAddressdeleteList = new ArrayList<PartnerAddress>();
			partnerAddressdeleteList = partnerAddressService.getPartnerAddressByPartnerId(partnerId);

		   Partner p = (Partner)partnerService.getById(partnerId);
         
		   if(p==null){
			   
				resultMap.put("failure", "不存在该客户");

				return "json";
			   
		   }
		   
			if(StringUtils.isNotBlank(partner.getTaxCode())){
				 Map m = new HashMap();
				 m.put("ownerId",ownerId);
				 m.put("taxCode",partner.getTaxCode());
			     Partner pr= partnerService.getPartnerByTaxCode(m);
			     if(pr!=null){
			     if(!pr.getId().equals(partnerId)){
                    
						resultMap.put("failure", "您好,拥有该税号的往来单位已经存在,不能重复增加");
						return "json";
			    	  	    	  
                     }
			   }
			}
		   		  
			JSONArray partnerAddressJson = JSONArray.fromObject(arr[1]);

			if (partnerAddressJson.size() != 0) {

				List<PartnerAddress> partnerAddressList = (List<PartnerAddress>) JSONArray.toCollection(partnerAddressJson, PartnerAddress.class);

				for (PartnerAddress partnerAddress : partnerAddressList) {

					partnerAddress = getPartnerAddress(partnerAddress);

					if (partnerAddress.getId() == null) {

						partnerAddressAddList.add(partnerAddress);
					} else {

						partnerAddressUpdateList.add(partnerAddress);
					}

				}

				try {

					if (partnerAddressAddList.size() != 0) {

						if (partnerAddressUpdateList.size() != 0) {

							for (PartnerAddress partnerList : partnerAddressUpdateList) {

								partnerAddressdeleteList.remove(partnerList);

							}
							partnerService.updateAndSaveAllwithDelete(partner,
									partnerAddressUpdateList,
									partnerAddressdeleteList,
									partnerAddressAddList);

						} else {
							partnerService.save(partner, partnerAddressAddList,partnerAddressdeleteList);
						}
					} else {

						if (partnerAddressUpdateList.size() != 0) {

							for (PartnerAddress partnerList : partnerAddressUpdateList) {

								partnerAddressdeleteList.remove(partnerList);

							}
		    				partnerService.updateAllwithDelete(partner,partnerAddressUpdateList,partnerAddressdeleteList);
						}
					}

				} catch (RuntimeException e) {

					resultMap.put("failure", "更新失败");
					return "json";

				}

			} else {
				partner.setPyCode(PinyinToolkit.cn2FirstSpell(partner.getName()));
				partnerService.updateAll(partner, partnerAddressdeleteList);

			}

		} else {
			/**
			 * 增加客户 partId等于null的情况
			 */

				partner.setOwnerId(ownerId);
             
				if(StringUtils.isNotBlank(partner.getTaxCode())){
				 Map m = new HashMap();
				 m.put("ownerId",ownerId);
				 m.put("taxCode",partner.getTaxCode());
			     Partner pr= partnerService.getPartnerByTaxCode(m);
				
			     if(pr!=null){

						resultMap.put("failure", "您好,拥有该税号的往来单位已经存在,不能重复增加");
						return "json";
			    	  	    	  
			   }
				}
				if(partner.getCompanyId()!=null&&partner.getCompanyId()!=0){
					
					if(partner.getCompanyId().equals(ownerId)){
						
						resultMap.put("failure", "您好,不能加自己为客户");
						return "json";
						
					}
					
					
					Map map = new HashMap();
					
					map.put("companyId", partner.getCompanyId());
					map.put("ownerId", ownerId);
					map.put("isDelete", 0);
					Partner p = partnerService.findPartnerByOwnerId(map);
					
					if(p!=null){
						
						resultMap.put("failure", "您好,该公司已经是你的客户,不能重复增加,请到客户列表查看");
						return "json";
						
					}	
				}		
				JSONArray partnerAddressJson = JSONArray.fromObject(arr[1]);

				if (partnerAddressJson.size() != 0) {

					List<PartnerAddress> partnerAddressList = (List<PartnerAddress>) JSONArray
							.toCollection(partnerAddressJson,
									PartnerAddress.class);

					for (PartnerAddress partnerAddress : partnerAddressList) {

						partnerAddress = getPartnerAddress(partnerAddress);

					}

					try {

						partnerService.createAll(partner, partnerAddressList);

					} catch (RuntimeException e) {
						resultMap.put("failure", "增加失败");
						return "json";
					}

				} else {

					partner.setPyCode(PinyinToolkit.cn2FirstSpell(partner
							.getName()));
					try {
		
						
						partnerService.create(partner);
					} catch (Exception e) {
						resultMap.put("failure", "增加失败");
                        e.printStackTrace();
					}

				}

		}
		resultMap.put("success", "OK");

		resultMap.put("partner", partner);
		return "json";

	}
	
	@SuppressWarnings("unchecked")
	public String add_Partner(){
		
		String cid = httpServletRequest.getParameter("companyId");
		String partnerId = httpServletRequest.getParameter("partnerId");
		
		sessionMessage = UserHolder.getCurrentSessionMessage();

		Integer ownerId = sessionMessage.getCompanyId();

		if(StringUtils.isNotBlank(cid)){
			
			Integer companyId = Integer.valueOf(cid);
			
			if(companyId.equals(ownerId)){
				
				resultMap.put("failure", "isSelf");
				return "json";
				
			}
			
			
			Map map = new HashMap();
			
			map.put("companyId", companyId);
			map.put("ownerId", ownerId);
			map.put("isDelete", 0);
			Partner p = partnerService.findPartnerByOwnerId(map);

		 	Map m= new HashMap();
			m.put("ownerId", companyId);
			m.put("companyId", ownerId);
			m.put("isDelete", 0);
			Partner p1 = partnerService.findPartnerByOwnerId(m);
			
			
			
			Map mm= new HashMap();
			mm.put("ownerId", ownerId);
			mm.put("companyId", companyId);
			mm.put("isDelete", 1);
			Partner p2 = partnerService.findPartnerByOwnerId(mm);
			
			
			if(p!=null){
				
				  if(p1==null){
					  
					  
					  resultMap.put("reason", "you partner already delete you");
					  resultMap.put("success", "OK");
				  }else{
					  
					  
						
						resultMap.put("failure", "alreadyPartner");
						
				  }

			
			}else{
					
			//p等于null,说明你曾经删除了该往来单位
			if(p1!=null){
				
				if(p2!=null){
					
				   if(StringUtils.isBlank(partnerId)){			
					try {
						p2.setIsDelete(0); 
						partnerService.updatePartner(p2);
					} catch (Exception e) {
						
						e.printStackTrace();
					}
					
					resultMap.put("failure", "you is success to revert");
					
				}else{
				
				resultMap.put("failure", "you is Partner to relation");
				
			  }
			}
		   }else{
			   
				resultMap.put("success", "OK");
		   } 
		  }			
		
		}

		return "json";
	}
	 
	
	//相互加为往来单位
	@SuppressWarnings("unchecked")
	public String addPartnerTogether() throws Exception{
		
		String cid = httpServletRequest.getParameter("companyId");
		
		//String relation = httpServletRequest.getParameter("relation");
		
		
		//String relationName = dictionaryReadOnlyService
		//.getDictionaryValue(DictionaryEnum.GROUP_PARTNER_RELATION,relation);
		
		sessionMessage = UserHolder.getCurrentSessionMessage();

		Integer ownerId = sessionMessage.getCompanyId();

		Integer senderId = sessionMessage.getUserId();
		if(StringUtils.isNotBlank(cid)){
			
			Integer companyId = Integer.valueOf(cid);
			
			if(companyId.equals(ownerId)){
				
				resultMap.put("failure", "isSelf");
				return "json";			
			}
			
			
			Map map = new HashMap();
			
			map.put("companyId", companyId);
			map.put("ownerId", ownerId);
			map.put("isDelete", 0);
			Partner p = partnerService.findPartnerByOwnerId(map);
			String acceptCompanyName = sessionMessage.getCompanyName();
			if(p!=null){
				
				resultMap.put("failure", "alreadyPartner");
				return "json";
				
			}
			try {
				Partner partner = new Partner();
				BeanUtils.copyProperties(partner,companyId);
				partner.setId(null);
				partner.setOwnerId(ownerId);
				partner.setGrantPrivacy(1);
				
				
				Partner partner1 = new Partner();
				BeanUtils.copyProperties(partner1,ownerId);
				partner1.setId(null);
				partner1.setOwnerId(companyId);
				partner1.setGrantPrivacy(1);
				
				
				
				Notice notice = new Notice();
				
				String jsArgs ="{acceptCompanyId:"+ownerId+"acceptCompanyName:"+acceptCompanyName+"}";
				
				notice.setNoticeType(1);
		        notice.setJsArgs(jsArgs);
		        notice.setJsModuleId("");
				notice.setSenderId(senderId);
				notice.setReceiverId(companyId);
				notice.setReceiveType(1);
				notice.setTitle(acceptCompanyName+"已接受您的邀请");
				notice.setContent(acceptCompanyName+"已接受您的邀请,并加您为往来单位");
				
				
				
				
				
				partnerService.createTogether(partner, partner1,notice);
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		resultMap.put("success", "OK");
		return "json";
	}
	
	
	

	private PartnerAddress getPartnerAddress(PartnerAddress partnerAddress) {

		Area area = (Area) areaService.getById(partnerAddress.getAreaId());
		if (area != null) {
			partnerAddress.setProvince(area.getProvince());
			partnerAddress.setCity(area.getCity());
			partnerAddress.setDistrict(area.getDistrict());
		}
		return partnerAddress;

	}

	public String delete() throws IOException {

		HttpServletRequest request = HttpUtil.getRequest();

		String id = request.getParameter("id");

		if (id != null) {

			Integer partnerId = Integer.valueOf(id);

			try {

				Partner partner = (Partner) partnerService.getById(partnerId);

				partner.setIsDelete(1);

				partnerService.deletePartner(partner);

			} catch (Exception e) {

				resultMap.put("failure", "删除失败");

				return "json";
			}

		} else {

			resultMap.put("failure", "该对象不存在");

			return "json";

		}

		return null;
	}

	public String queryCompanyMessage(){
		
		
		 String queryParam = httpServletRequest.getParameter("queryParam");
		 String partnerId = httpServletRequest.getParameter("partnerId");
		 
		    if(StringUtils.isBlank(queryParam)){
		    	 
		    	resultMap.put("failure", "查询条件不能为空");

				return "json";
		    }
		    if(StringUtils.isBlank(partnerId)){
		    	 
		    	resultMap.put("failure", "该客户不存在");

				return "json";
		    }
		 
		 Integer param = Integer.valueOf(queryParam);    
		  
		 Integer id =  Integer.valueOf(partnerId);
		
		 Partner partner = (Partner)partnerService.getById(id);
		 
		 if(partner==null){
			 
			 resultMap.put("failure", "该客户不存在");

			 return "json";
		 }
		 
		 
		 if(param==1){
			 
			 String contactorIdentityCode=partner.getContactorIdentityCode();
			 
			 if(StringUtils.isBlank(contactorIdentityCode)){
				 
				 contactorIdentityCode="-1";
			 }		 
			 List<Company> companyList = companyService.getByContactorIdentityCode(contactorIdentityCode,1);
			 
			 resultMap.put("root", companyList);
			 
			 return "json";
			 
		    }else if(param==2){
			List <Company> companys = new ArrayList<Company>(); 
		    Company	company = companyService.getCompanyByTaxCode(partner.getTaxCode(),1);
		    
		    if(company==null){
		    	
		    	 resultMap.put("root", companys);
		    	 
		    }else{		    	
			    
			     resultMap.put("root", company);	
		    	
		    }	
		    return "json";
			 
		 }else{
			 
			 resultMap.put("failure", "查询条件不能为空");

			 return "json";
			 
		 }
		
	}
	
	public String updateMessage(){
		
		 String partnerId = httpServletRequest.getParameter("partnerId");
		 String cp = httpServletRequest.getParameter("companyId");
		 
		 if(StringUtils.isBlank(partnerId)){
	    	 
		    	resultMap.put("failure", "该客户不存在");

				return "json";
		    }
		 
		 if(StringUtils.isBlank(cp)){
	    	 
		    	resultMap.put("failure", "该公司不存在");

				return "json";
		    }
		 
		 Integer id =  Integer.valueOf(partnerId);
		 Integer companyId =  Integer.valueOf(cp);	
		 Partner partner = (Partner)partnerService.getById(id);
		 
		 if(partner==null){
			 
			 resultMap.put("failure", "该客户不存在");

			 return "json";
		 }
		 
		 partner.setCompanyId(companyId);
		
		 try {
			partnerService.updatePartner(partner);
		} catch (Exception e) {
		
			resultMap.put("failure", "该客户不存在");

			return "json";
		}
		 
		resultMap.put("success", "OK");

		resultMap.put("partner", partner);
		
		return "json";
	}
	
	
	public String searchPermission(){
		
		
		sessionMessage = UserHolder.getCurrentSessionMessage();

		Integer ownerId = sessionMessage.getCompanyId();

		Company company = (Company)companyService.getById(ownerId);
		
		if(company==null){
			
			resultMap.put("failure", "该公司不存在");

			return "json";
			
		}

		
		/**if(company.getCertifyingStatus()==null||company.getPaid()==null){
			
			if(company.getCertifyingStatus()==null){
				
				company.setCertifyingStatus(0);
				
			}
			
			if(company.getPaid()==null){
				
				company.setPaid(0);
			}
			companyService.update(company);
		}*/
		

		if(company.getCertifyingStatus()==3||company.getCertifyingStatus()==4||company.getCertifyingStatus()==2&&company.getRealType()==1){
			
			if(company.getPaid()==1){
				
				resultMap.put("success", "OK");
				
			}else{
				
				resultMap.put("failure", "notPaid");
				
			}
		}else{
			
			
			 resultMap.put("failure", "notCertify");
			
		}
		
		return "json";
		
	}
	
	
	
	
	
	
	public String searchCompany(){
		
		    String queryParam = httpServletRequest.getParameter("queryParam");
		    
		    if(StringUtils.isNotBlank(queryParam)){
		    	
		    	JSONObject jsonObject = JSONObject.fromObject(queryParam);	
		    	
		    	
				  String condition=jsonObject.getString("checkCondition");
				    
				  
	        	   String conditionText = jsonObject.getString("conditionText");
	        	   
	        	   List<Company> companyList =null;
	        	   
	        	   if(StringUtils.isBlank(conditionText)){
	        		   
	        		   conditionText="-1";
	        		   
	        	   }
			         if("1".equals(condition)){			        	
			        	    
			        	    try {
								companyList = companyService.getByContactorIdentityCode(conditionText,1);
								
								for(Company company:companyList){
									
									company.setTaxCode(JoinStringUtil.getHideCode(company.getTaxCode(),6));
									company.setContactorIdentityCode(JoinStringUtil.getHideCode(company.getContactorIdentityCode(),6));							
									
								}
								
								 resultMap.put("root", companyList);
							} catch (Exception e) {
								 resultMap.put("failure", "查找失败");
								 return "json";
							} 
			        	 
			         }else if("2".equals(condition)){
			        	 
			        	    try {
								Company company = companyService.getCompanyByTaxCode(conditionText,1);
								
								if(company==null){
									companyList = new ArrayList<Company>(); 
									resultMap.put("root", companyList);
								}else{
									
									company.setTaxCode(JoinStringUtil.getHideCode(company.getTaxCode(),6));
									company.setContactorIdentityCode(JoinStringUtil.getHideCode(company.getContactorIdentityCode(),6));
				
									resultMap.put("root", company);									
								}
							
							} catch (Exception e) {
								 resultMap.put("failure", "查找失败");
								 return "json";

							}
			        	 
			        	 
			         }else{
						 
						 resultMap.put("failure", "查询条件不能为空");

						 return "json";
						 
					 }   	 
			  			
		    }
		       resultMap.put("success", "OK");
			   return "json";  
		  
	}
	
	public String sendRejectNotice(){

		String reason = httpServletRequest.getParameter("reason");
		String cid = httpServletRequest.getParameter("companyId");
		
		sessionMessage = UserHolder.getCurrentSessionMessage();

		Integer ownerId = sessionMessage.getCompanyId();

		Integer senderId = sessionMessage.getUserId();
		
		Integer companyId=null;
		
		if(StringUtils.isNotBlank(cid)){
			
			 companyId = Integer.valueOf(cid);
		
		}
			
		
		String acceptCompanyName = sessionMessage.getCompanyName();
		
		Notice notice = new Notice();
		
		String jsArgs ="{acceptCompanyId:"+ownerId+"reason:"+reason+"acceptCompanyName:"+acceptCompanyName+"}";
		
		notice.setNoticeType(1);
        notice.setJsArgs(jsArgs);
        notice.setJsModuleId("");
		notice.setSenderId(senderId);
		notice.setReceiverId(companyId);
		notice.setReceiveType(1);
		notice.setTitle(acceptCompanyName+"拒绝了您的邀请");
		
		if(StringUtils.isBlank(reason)){
		
		   notice.setContent(acceptCompanyName+"拒绝了您的邀请");
		
		}else{
			
		   notice.setContent(acceptCompanyName+"拒绝了您的邀请,理由是:"+reason);
		}
		
		try {
			noticeService.send(notice, 24);
		} catch (Exception e) {
			
			e.printStackTrace();
			
			resultMap.put("failure", "发送消息失败");
			
			return "json";
		}
		
		resultMap.put("success", "OK");
		
		return "json";
	}
	
	
	
	public String sendNotice(){
		
		SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();
		String receiverId = httpServletRequest.getParameter("receiverId");
		String reason = httpServletRequest.getParameter("reason");
		String relation = httpServletRequest.getParameter("relation");
		String pid = httpServletRequest.getParameter("partnerId");
		
		 if(StringUtils.isBlank(receiverId)){
	    	 
		    	resultMap.put("failure", "该公司不存在");

				return "json";
		    }
		 
		 Integer partnerId=0;
		 
		 if(StringUtils.isNotBlank(pid)){
	    	 
			 partnerId=Integer.valueOf(pid);
			 
		    }
		
		 Integer companyId =Integer.valueOf(receiverId);
		 
		 
		Integer senderId = sessionMessage.getUserId();
		Integer ownerId =sessionMessage.getCompanyId();	
		
		//Company company = (Company)companyService.getById(ownerId);
		
		String inviteCompanyName = sessionMessage.getCompanyName();
		
		Notice notice = new Notice();
		
		String jsArgs ="{inviteCompanyId:"+ownerId+",reason:'"+reason+"',relation:'"+relation+"',inviteCompanyName:'"+inviteCompanyName+"',partnerId:"+partnerId+"}";
		
		notice.setNoticeType(1);
        notice.setJsArgs(jsArgs);
        notice.setJsModuleId("acceptAddPartner");
		notice.setSenderId(senderId);
		notice.setReceiverId(companyId);
		notice.setReceiveType(Notice.RECEIVE_TYPE_COMP);
		notice.setTitle(inviteCompanyName+"已加您为往来单位");
		notice.setContent(inviteCompanyName+"已加您为往来单位,并请求加入您的往来单位,并请求查看您的联系方式");
		
		try {
			noticeService.send(notice, 24);
		} catch (Exception e) {
			
			e.printStackTrace();
			
			resultMap.put("failure", "发送消息失败");
			
			return "json";
		}
		
		resultMap.put("success", "OK");
		
		return "json";
	}
    //恢复未认证公司未往来单位
	public String revertPartner(){
		
		String id =httpServletRequest.getParameter("id");
		
		if(StringUtils.isBlank(id)){
			
            resultMap.put("failure", "上传参数异常");
			
			return "json";
			
		}
		Integer partnerId = Integer.valueOf(id);
		
		Partner partner = (Partner)partnerService.getById(partnerId);
		
		partner.setIsDelete(0);
		
		partnerService.updatePartner(partner);
		
		resultMap.put("success", "OK");
		
		return "json";
	}
	
	
	
	public String getPartnerByLikeName() {
		sessionMessage = UserHolder.getCurrentSessionMessage();
		List<Partner> partners = partnerService
				.getPartnerByOwnerIdaAndLikeName(sessionMessage.getCompanyId(),
						queryParam);
		jsonResult = JSONObject.fromObject(JSONArray.fromObject(partners));
		return SUCCESS;
	}

	/**
	 * *根据查询参数查询往来关系:1 供应商 2 即是客户也是供应商的partner
	 * 
	 * @author jiwei.yi
	 */
	@SuppressWarnings("unchecked")
	public String queryPartner() {
		ListModel<Partner> partnerlistModel = generateListModelParams();
		ListModel<Partner> pModel = partnerService
				.getPartnersByPagingCondition(partnerlistModel, queryParam,
						type,qualify);
		jsonResult.put("totalProperty", pModel.getTotal());
		jsonResult.put("root", JSONArray.fromObject(pModel.getResult()));
		return SUCCESS;
	}

	public JSONObject getJsonResult() {
		return jsonResult;
	}

	public void setJsonResult(JSONObject jsonResult) {
		this.jsonResult = jsonResult;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}
	
	
	private PartnerListModel getModelUtil(HttpServletRequest request) {
		
		PartnerListModel partnerListModel=new PartnerListModel();
		partnerListModel.setPageSize(limit);
		partnerListModel.setStart(start);
		partnerListModel.setOrderBy(sort);
		partnerListModel.setDesc(dir.equalsIgnoreCase("desc") ? true : false);
		String jsonAll = request.getParameter("jsonAll");
		
		if (StringUtils.isNotBlank(jsonAll)) {

			JSONObject jsonObject = JSONObject.fromObject(jsonAll);

				
			partnerListModel.setIsDelete(jsonObject.getString("isDelete"));
			partnerListModel.setRelation(jsonObject.getString("relation"));
			partnerListModel.setContactor(jsonObject.getString("contactor"));
			partnerListModel.setPyCode(jsonObject.getString("pyCode"));
			partnerListModel.setName(jsonObject.getString("name"));
			
		}
				
		return partnerListModel;
	}

	public String getQualify() {
		return qualify;
	}

	public void setQualify(String qualify) {
		this.qualify = qualify;
	}
	
	@SuppressWarnings("unchecked")
	public String query_condition(){
		
		String cid = httpServletRequest.getParameter("companyId");
		
		SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();
		
		Integer ownerId = sessionMessage.getCompanyId();
		
		if(StringUtils.isBlank(cid)){
			
			
			return "json";
		}
		
		Integer companyId = Integer.valueOf(cid);
		
	    Company c = (Company)companyService.getById(companyId);
		
	    
	    Map map = new HashMap();
	    
	    String texCode = c.getTaxCode();
	    String contactorIdentityCode = c.getContactorIdentityCode();
	    
	    
	    if(StringUtils.isBlank(texCode)){
	    	
	    	texCode="-1";
	    	
	    }
	    
	    if(StringUtils.isBlank(contactorIdentityCode)){
	    	
	    	contactorIdentityCode="-1";
	    	
	    }
	    
	    map.put("taxCode",texCode);
	    map.put("contactorIdentityCode", contactorIdentityCode);
	    map.put("ownerId", ownerId);
	    List<Partner> partners = partnerService.findPartnerByCondition(map);
	    
	    resultMap.put("root",partners);
	    
	    return "json";
	} 
}
